package IOtest;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Account{
    private String cardId;
    //余额
    private double money;
    public Account(String cardId,double money){
        this.cardId=cardId;
        this.money=money;
    }
    public String getCardId(){
        return cardId;
    }
    public double getMoney(){
        return money;
    }
    public void setMoney(double money){
        this.money=money;
    }
    private final Lock lock = new ReentrantLock();
    //取钱
    public void drawMoney(double money) {
        String name = Thread.currentThread().getName();
        //加锁
        lock.lock();
        try {
            if (this.money >= money) {
                //取钱
                System.out.println(name + "来取钱成功，取走：" + money);
                this.money = this.money - money;
                System.out.println(name + "取钱后剩余：" + this.money);
            } else {
                System.out.println(name + "来取钱失败，余额不足");
            }
        }finally{
            //释放锁
            lock.unlock();
        }
    }
}

class DrawThread extends Thread {
    // private Account acc;
    private Account acc;

    public DrawThread(Account acc, String name) {
        super(name);
        this.acc = acc;
    }

    @Override
    public void run() {
        acc.drawMoney(1000);
    }
}

    public class ThreadTest3 {
        public static void main(String[] args) {
            //创建账户对象
            Account acc = new Account("ICBC-111", 1000);
            //创建两个线程对象
            DrawThread t1 = new DrawThread(acc, "小帅");
            t1.setPriority(Thread.MIN_PRIORITY);
            t1.start();
            DrawThread t2 = new DrawThread(acc, "小美");
            t2.setPriority(Thread.MAX_PRIORITY);
            t2.start();
        }
    }
